namespace SubSonic
{
    using System;
    using System.Collections.Generic;
    using System.Data.Common;

    public class SharedDbConnectionScope : IDisposable
    {
        [ThreadStatic]
        private static Stack<SharedDbConnectionScope> __instances;
        private readonly DataProvider _dataProvider;
        private bool _disposed;

        public SharedDbConnectionScope() : this(DataService.Provider)
        {
        }

        public SharedDbConnectionScope(DataProvider dataProvider)
        {
            if (dataProvider == null)
            {
                throw new ArgumentNullException("dataProvider");
            }
            this._dataProvider = dataProvider;
            this._dataProvider.InitializeSharedConnection();
            if (__instances == null)
            {
                __instances = new Stack<SharedDbConnectionScope>();
            }
            __instances.Push(this);
        }

        public SharedDbConnectionScope(string connectionString) : this(DataService.Provider, connectionString)
        {
        }

        public SharedDbConnectionScope(DataProvider dataProvider, string connectionString)
        {
            if (dataProvider == null)
            {
                throw new ArgumentNullException("dataProvider");
            }
            if (connectionString == null)
            {
                throw new ArgumentNullException("connectionString");
            }
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("connectionString can not be empty");
            }
            this._dataProvider = dataProvider;
            this._dataProvider.InitializeSharedConnection(connectionString);
            if (__instances == null)
            {
                __instances = new Stack<SharedDbConnectionScope>();
            }
            __instances.Push(this);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing)
        {
            if (!this._disposed && disposing)
            {
                __instances.Pop();
                if (__instances.Count == 0)
                {
                    this._dataProvider.ResetSharedConnection();
                }
                this._disposed = true;
            }
        }

        public DbConnection CurrentConnection
        {
            get
            {
                return this._dataProvider.CurrentSharedConnection;
            }
        }
    }
}

